package com.zidian.teacher.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import com.zidian.teacher.R;
import com.zidian.teacher.api.LoginResult;
import com.zidian.teacher.api.TeacherApi;
import com.zidian.teacher.common.Constant;
import com.zidian.teacher.common.ToolBarActivity;
import com.zidian.teacher.utils.ProgressBarBlackUtil;

/**
 * Created by Administrator on 2016/9/13 0013.
 * <p>
 * 登录界面
 */
public class LoginActivity extends AppCompatActivity implements TextWatcher {


    @Bind(R.id.student_account)
    EditText studentAccount;
    @Bind(R.id.student_password)
    EditText studentPassword;
    @Bind(R.id.login_btn)
    Button loginBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferences sharedPreferences = getSharedPreferences(Constant.USER_INFO_KEY, Context.MODE_PRIVATE);
        if (sharedPreferences.getBoolean("isLogin", false)) {

            startActivity(new Intent(this,MainActivity.class));
        } else {
            setContentView(R.layout.activity_login);
            setTitle("登录");
            ButterKnife.bind(this);
            loginBtn.setEnabled(false);
            studentAccount.setText(sharedPreferences.getString("account", ""));
            initView();
        }
    }

    private void initView() {
        studentAccount.addTextChangedListener(this);
        studentPassword.addTextChangedListener(this);
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginUpdata();
                //rxLogin();
            }
        });

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

        boolean account = studentAccount.getText().toString().trim().length() > 0;
        boolean password = studentPassword.getText().toString().trim().length() > 0;

        if (account && password) {
            loginBtn.setEnabled(true);
        } else {
            loginBtn.setEnabled(false);
        }

    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    /**
     * Created by Administrator on 2016/9/13 0013.
     * <p>
     * 登录方法
     */
    private void loginUpdata() {
        String loginUrl = Constant.URL_GOAL + "shiro/loginTeacher";
        HashMap<String, String> map = new HashMap<>();
        map.put("username", studentAccount.getText().toString().trim());
        map.put("password", studentPassword.getText().toString().trim());

        ProgressBarBlackUtil.loadShow(this);

        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Snackbar.make(loginBtn,e.getMessage(),Snackbar.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                ProgressBarBlackUtil.loadCancel();
                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {
                        Snackbar.make(loginBtn,jsonObject.getString("message"),Snackbar.LENGTH_SHORT).show();

                        return;
                    } else {
                        SharedPreferences sharedPreferences = getSharedPreferences(Constant.USER_INFO_KEY, Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
                        editor.putString("account", studentAccount.getText().toString().trim());
                        editor.putString("teacherId", jsonObject.getString("teacherId"));
                        editor.putString("teacherName", jsonObject.getString("teacherName"));
                        editor.putString("token", jsonObject.getString("token"));
                        editor.putBoolean("isLogin", true);
                        editor.commit();
                        Snackbar.make(loginBtn,"登录成功",Snackbar.LENGTH_SHORT).show();
                        startActivity(new Intent(LoginActivity.this,MainActivity.class));
                        finish();
                        return;
                    }

                } catch (JSONException e) {

                }

            }
        });
    }
    private void rxLogin(){
        String username = studentAccount.getText().toString().trim();
        String password = studentPassword.getText().toString().trim();
        TeacherApi.getInstance().login(username,password)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<LoginResult>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        Snackbar.make(loginBtn,"失败",Snackbar.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNext(LoginResult loginResult) {
                        Snackbar.make(loginBtn,loginResult.toString(),Snackbar.LENGTH_SHORT).show();
                    }
                });

    }

}
